package com.wpx.log.core.handler.param;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;
import com.wpx.log.core.module.LogParam;
import com.wpx.log.util.Utils;

@Component
public class ILogJsonParamTypePolicy implements ILogParamTypePolicy {

	@Override
	public String type() {
		return "application/json";
	}

	@Override
	public void parseParam(LogContext logContext, LogRequestContext logRequestContext, Field logField, final List<LogParam> params) {
		JSONObject josn = new JSONObject();
		try {
			HttpServletRequest request = logRequestContext.getHttpServletRequest();
			String string = request.getReader().lines().collect(Collectors.joining());
			if(Utils.isJson(string)) {
				josn = JSON.parseObject(string);	
			}else {
				params.add(new LogParam("", string, LogParam.TYPE_BASE));
				return;
			}			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Set<Entry<String, Object>> entrySet = josn.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			LogParam param = null;
			Object value = entry.getValue();
			if(value != null && Utils.isJson(value.toString())) {
				param = new LogParam(entry.getKey(), value, LogParam.TYPE_JSON);
			}else {
				param = new LogParam(entry.getKey(), value, LogParam.TYPE_BASE);
			}		
			params.add(param);
		}
	}

}
